using System;
using System.Collections.Generic;
using System.Linq;
using axCommerce.Data.Interface;

namespace axCommerce.Data
{
	public partial class Rating : ISimpleData
	{
		public static List<Rating> GetProductRatings(int iProductId)
		{
			return Search(new Rating
			              	{
			              		ProductId = iProductId,
								IsDeleted = false
			              	});
		}

		public static List<Rating> GetCommentRatings(int iCommentId)
		{
			return Search(new Rating
			              	{
			              		CommentId = iCommentId,
								IsDeleted = false
			              	});
		}

		public void Save()
		{
			CreatedDate = DateTime.Now;
			LastModifiedDate = DateTime.Now;
			IsDeleted = false;

			Insert();
		}

		public void UpdateInstance()
		{
			LastModifiedDate = DateTime.Now;

			Update();
		}

		public void MarkAsDeleted()
		{
			LastModifiedDate = DateTime.Now;
			IsDeleted = true;

			Update();
		}
	}

	public class RatingCollection : List<Rating>
	{
		public double Average { get; private set; }

		public RatingCollection(int iKeyValue, bool bIsProduct)
		{
			AddRange(bIsProduct ? Rating.GetProductRatings(iKeyValue) : Rating.GetCommentRatings(iKeyValue));
			GetAverageValue();
		}

		private void GetAverageValue()
		{
			Average = this.Average(rating => rating.RatingValue != null ? rating.RatingValue.Value : 0);
		}
	}
}

